/*
 * Copyright (c) 2024 iSOFT INFRASTRUCTURE SOFTWARE CO., LTD.
 * easyAda is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */

#ifndef CAPS_CNODE_H
#define CAPS_CNODE_H

#include <caps/capability.h>
#include <core/object.h>

#define GUARDBITS    (24)
#define GUARDLENBITS (5)
#define RADIXBITS    (3)
#define RADIXBASE    (4)

#define GUARDOFFSET    (0)
#define GUARDLENOFFSET (GUARDBITS)
#define RADIXOFFSET    (GUARDBITS + GUARDLENBITS)

static inline unsigned int cap_cnode_get_guardlen(capability_t *cap)
{
    return (cap_get_long_info(cap) >> GUARDLENOFFSET) & lowbitsmask(GUARDLENBITS);
}

static inline unsigned int cap_cnode_get_guard(capability_t *cap)
{
    return (cap_get_long_info(cap) >> GUARDOFFSET) & lowbitsmask(GUARDBITS);
}

static inline unsigned int cap_cnode_get_radix(capability_t *cap)
{
    return ((cap_get_long_info(cap) >> RADIXOFFSET) & lowbitsmask(RADIXBITS)) + RADIXBASE;
}

static inline capability_t *cap_cnode_get_obj(capability_t *cap)
{
    return (capability_t *)(cap_get_short_info(cap) << CAP_TYPE_BITS);
}

void          cap_cnode_recycle(capability_t *cnode);
capability_t *cap_cnode_get_audit(capability_t *cnode);

static inline int cap_cnode_get(capability_t *cnode)
{
    return object_get((object_t *)&cap_cnode_get_audit(cnode)->next);
}

static inline void cap_cnode_put(capability_t *cnode)
{
    if (object_put((object_t *)&cap_cnode_get_audit(cnode)->next, 0, 0) == 0) {
        cap_cnode_recycle(cnode);
    }
}

static inline void cspace_audit_init(capability_t *audit)
{
    assert(sizeof(void *) * 2 == sizeof(object_t));
    cap_basic_init(audit, CAP_AUDIT);
    object_init((object_t *)&audit->next);
}

static inline void cap_cnode_copy(capability_t *to, capability_t *from)
{
    cap_cnode_get(from);
    cap_copy(to, from);
}

void          cap_cnode_init(capability_t *cap, capability_t *cnode, unsigned int guardlen, unsigned int guard,
                             unsigned int radix);
capability_t *cnode_cptr_lookup(capability_t *cnode, unsigned long cptr, unsigned int bits);
void cap_cnode_dispatcher(capability_t *cap, unsigned long op, unsigned long m0, unsigned long m1, unsigned long m2,
                          unsigned long m3, unsigned long m4, unsigned long m5);

#endif
